package com.work.demo.test;

import cn.hutool.core.io.FileUtil;
import com.alibaba.fastjson.JSON;
import org.junit.Test;

import java.util.*;
import java.util.concurrent.*;
import java.util.concurrent.atomic.AtomicInteger;
import java.util.concurrent.locks.ReentrantLock;
import java.util.concurrent.locks.StampedLock;

/**
 * @ClassName : ExecutorServiceDemo
 * @Description : 线程池demo
 * @Author : LinYa
 * @Date: 2022/1/4  11:05
 */
public class ExecutorServiceDemo {


	private static final int TASK_SIZE = 100;

	private static final int NTHREADS = 10;

	private static final ExecutorService exec = Executors.newFixedThreadPool(NTHREADS);


	private final AtomicInteger ctl = new AtomicInteger(ctlOf(STOP, 0));
	private static final int COUNT_BITS = Integer.SIZE - 3;
	private static final int CAPACITY = (1 << COUNT_BITS) - 1;

	// runState is stored in the high-order bits
	private static final int RUNNING = -1 << COUNT_BITS;
	private static final int SHUTDOWN = 0 << COUNT_BITS;
	private static final int STOP = 1 << COUNT_BITS;
	private static final int TIDYING = 2 << COUNT_BITS;
	private static final int TERMINATED = 3 << COUNT_BITS;

	private static int ctlOf(int rs, int wc) {
		return rs | wc;
	}


	@Test
	public void submitTest() {
		ExecutorService pool = Executors.newFixedThreadPool(TASK_SIZE);

		List<Future> list = new ArrayList<>();
		for (int i = 0; i < TASK_SIZE; i++) {

			//无返回值
//			pool.execute(myCallable1(i+""));

			//有返回值
			Future<String> f = pool.submit(myCallable(i + ""));
			list.add(f);

		}

		pool.shutdown();

		//打印返回值
		list.forEach(future -> {
			try {
				System.out.println(future.get().toString());
			} catch (InterruptedException | ExecutionException e) {
				e.printStackTrace();
			}
		});

	}


	private static Callable<String> myCallable(String name) {

		return () -> "第" + name + "个线程执行";
	}


	private static Runnable myCallable1(String name) {

		return () -> System.out.println("第" + name + "个线程执行");

	}


	@Test
	public void execute() {
		ExecutorService executorService = Executors.newFixedThreadPool(10);

		while (true) {
			executorService.execute(() -> {
				System.out.println(Thread.currentThread().getName() + " is running ...");
				try {
					Thread.sleep(100);
				} catch (InterruptedException e) {
					e.printStackTrace();
				}
			});
		}

	}

	@Test
	public void ScheduledExecutorServiceDemo() {
		ScheduledExecutorService service = Executors.newScheduledThreadPool(3);
		service.schedule(() -> System.out.println("延迟三秒"), 3, TimeUnit.SECONDS);

		service.scheduleAtFixedRate(() -> System.out.println("延迟一秒后每三秒执行一次"), 1, 3, TimeUnit.SECONDS);


		do {

		} while (!service.isShutdown());


	}

	@Test
	public void SingleThreadExecutor() {
		ExecutorService executorService = Executors.newFixedThreadPool(10);
		ExecutorService service = Executors.newSingleThreadExecutor();

		service.execute(() -> System.out.println(Thread.currentThread().getName() + "执行完后执行"));
		service.execute(() -> System.out.println(Thread.currentThread().getName() + "执行完后执行213123"));


		executorService.execute(() -> System.out.println(Thread.currentThread().getName() + "我要睡一会儿"));
		executorService.execute(() -> System.out.println(Thread.currentThread().getName() + "我要睡一会儿123123"));


		System.out.println(Thread.currentThread().getName() + "我在这里");

		System.out.println(Thread.currentThread().getName() + "我在这里1223");
		service.shutdown();


		executorService.shutdown();


	}

	@Test
	public void TaskExecutionWebServer() {

		ReentrantLock lock = new ReentrantLock();

		StampedLock stampedLock = new StampedLock();
		stampedLock.tryOptimisticRead();

		while (true) {


			Runnable runnable = () -> System.out.println(Thread.currentThread().getName());

			exec.execute(runnable);
		}


	}

	@Test
	public void test() {

		String path = "C:\\Users\\admin\\Documents\\WXWork\\1688851079825408\\Cache\\File\\2021-12\\breast_hetero_host.csv";

		Map<String, Object> map = new HashMap<>(10);
		List<String> utf8Lines = FileUtil.readUtf8Lines(FileUtil.file(path));
		System.out.println(utf8Lines.get(0));
		System.out.println(utf8Lines.get(1));
		int idIndex = 2;
		List<Object[]> strings = new ArrayList<>(10);
		for (int i = 0; i < utf8Lines.size(); i++) {
			String s = utf8Lines.get(i);
			String[] split = s.split(",");
			if (i == 0) {
				map.put("headers", split);
				for (int j = 0; j < split.length; j++) {
					String s1 = split[j];
					if ("id".equals(s1)) {
						idIndex = j;
						break;
					}
				}
			} else {
				Object[] objects = new Object[split.length];
				objects[idIndex] = split[idIndex];
				for (int y = 0; y < split.length; y++) {
					if (y == idIndex) {
						continue;
					}
					objects[y] = Double.valueOf(split[y]);
				}
				strings.add(objects);
			}
		}
		map.put("data", strings);
		System.out.println(JSON.toJSONString(map));
	}

	@Test
	public void optionalTest() {
		new ConcurrentHashMap<>();
		Map<String, Object> map = new HashMap<>(10);

		Object posLabelObj = map.get("pos_label");
		Optional<Object> optional = Optional.ofNullable(posLabelObj);
		optional.ifPresent(ps -> map.put("pos_label", Integer.valueOf(String.valueOf(ps))));
		optional.orElse(map.put("pos_label", 1));
		System.out.println(map);
	}


	private static final int HASH_BITS = 0x7fffffff;

	private static final int spread(int h) {
		return (h ^ (h >>> 16)) & HASH_BITS;
	}


	@Test
	public void stringTest() {

		int k = 12;
		int v = 11;


		System.out.println(k | v);
		System.out.println(k & v);
		System.out.println(k ^ v);
		System.out.println(~v);
	}


}
